//
//  ConfigManager.cpp
//  TRKUTIL
//
//  Created by 李通洲 on 15/1/24.
//  Copyright (c) 2015年 Wicresoft. All rights reserved.
//
 
#include <cstdio>
#include <cstring>
#include <string>
#include <fstream>

#include "Helper.hpp"
#include "ConfigManager.hpp"

#define COMMAND_STR "Command="
#define LOGLEVEL_STR "LogLevel="

namespace {
    inline std::string parseCommand(const std::string& strLine) {
        return strLine.substr(std::strlen(COMMAND_STR));
    }

    inline LogLevel parseLogLevel(const std::string& strLine) {
        std::string levelStr = strLine.substr(std::strlen(LOGLEVEL_STR));
        if (levelStr == "Info") {
            return Info;
        } else if (levelStr == "Warning") {
            return Warning;
        } else if (levelStr == "Error") {
            return Error;
        } else if (levelStr == "None") {
            return None;
        } else {
            panic("Unknown Log level is found");
            return Unknown;
        }
    }
}

std::string LoadConfig() {
    std::ifstream ifs((GetCurrentExecutablePath() + "TRKUTIL.conf").c_str());
    if (!ifs.is_open()) {
        panic("Config file (TRKUTIL.conf) is not found!\n"
              "The config file should follow the format below:\n"
              "\t" COMMAND_STR "[[Command for msend]]\n"
              "\t" LOGLEVEL_STR "[Info|Warning|Error|None]");
    }

    std::string command;
    LogLevel logLevel = Unknown;
    
    {
        std::string strLine;
        while (std::getline(ifs, strLine)) {
#ifndef _WIN32
            if (strLine[strLine.length() - 1] == '\r') {
                strLine.resize(strLine.length() - 1);  // Handle CRLF in linux
            }
#endif
            if (strLine.find(COMMAND_STR) == 0) {
                command = parseCommand(strLine);
            } else if (strLine.find(LOGLEVEL_STR) == 0) {
                logLevel = parseLogLevel(strLine);
            }
        }
    }
    
    if (logLevel == Unknown) {
        LogManager::getInstance().LogWarning("Configuring Log level is not found in the config file, default to [INFO]");
        logLevel = Info;
    }
    if (command.length() < std::strlen("msend"))
        panic("Fail to read the command line!\nCheck the config file please");
    
    LogManager::getInstance().GlobalLogLevel = logLevel;
    
    return command;
}
